import dynamic from 'next/dynamic'
import { useEffect, useState } from 'react'
import { useRouter } from 'next/router'
import Seo from '../../../core/components/Seo'
import Promocrumb from '../../../lib/promo/components/Promocrumb'
import { fetchPromoItemsSolr, fetchVariantSolr } from '../../../api/promoApi'
import LogoSpinner from '../../../core/components/elements/Spinner/LogoSpinner.jsx'
import ProductPromoCard from '../../../../src-migrate/modules/product-promo/components/Card'
import { IPromotion } from '../../../../src-migrate/types/promotion'
import React from 'react'
import { SolrResponse } from "../../../../src-migrate/types/solr.ts";
import DesktopView from '../../../core/components/views/DesktopView';
import 'swiper/swiper-bundle.css';
import useDevice from '../../../core/hooks/useDevice'
import ProductFilterDesktop from '../../../lib/product/components/ProductFilterDesktop';
import { HStack, Image, Tag, TagCloseButton, TagLabel } from '@chakra-ui/react';
import { formatCurrency } from '../../../core/utils/formatValue';
import Pagination from '../../../core/components/elements/Pagination/Pagination';
import { cons } from 'lodash-contrib'

const BasicLayout = dynamic(() => import('../../../core/components/layouts/BasicLayout'))

export default function PromoDetail() {
  const router = useRouter()
  const { slug = '', brand, category } = router.query
  const [promoItems, setPromoItems] = useState<any[]>([])
  const [promoData, setPromoData] = useState<IPromotion[] | null>(null)
  const [currentPage, setCurrentPage] = useState(1);
  const itemsPerPage = 12; // Jumlah item yang ingin ditampilkan per halaman
  const startIndex = (currentPage - 1) * itemsPerPage;
  const endIndex = Math.min(startIndex + itemsPerPage, promoData?.length || 0);
  const [loading, setLoading] = useState(true);
  const { isMobile, isDesktop } = useDevice()
  const [brands, setBrands] = useState<Brand[]>([]);
  const [categories, setCategories] = useState<Category[]>([]);

  interface Brand {
    brand: string;
    qty: number;
  }

  interface Category {
    name: string;
    qty: number;
  }

  useEffect(() => {
    const loadPromo = async () => {
      setLoading(true);
      const brandsData: Brand[] = [];
      const categoriesData: Category[] = [];

      
      try {
        const items = await fetchPromoItemsSolr(`type_value_s:${Array.isArray(slug) ? slug[0] : slug}`)
        setPromoItems(items)
        
        if (items.length === 0) {
          setPromoData([])
          setLoading(false);
          return;
          }
          
          const promoDataPromises = items.map(async (item) => {
            // const queryParams = new URLSearchParams({ q: `id:${item.id}` })
            console.log("produk id",item.product_id)
            
            try { 
              if(brand  &&  category){
                const response = await fetchVariantSolr(`id:${item.product_id} && manufacture_name_s:${brand} && category_name :${category}`);
                const product = response.response.docs[0];
                const product_id = product.id
                console.log("data brand ",brand)
                console.log("data respon varian ",product)
                console.log("data ID respon varian ",product_id)
                const response2 = await  fetchPromoItemsSolr( `type_value_s:${Array.isArray(slug) ? slug[0] : slug} && product_ids:${product_id}`)
                console.log("data response2 ",response2)
                return response2;
              }else if(brand){ // belum bisa menangani lebih dari 1 brand
                const response = await fetchVariantSolr(`id:${item.product_id} && manufacture_name_s:${brand}`);
                const product = response.response.docs[0];
                const product_id = product.id
                console.log("data brand ",brand)
                console.log("data respon varian ",product)              
                console.log("data ID respon varian ",product_id)
                const response2 = await  fetchPromoItemsSolr( `type_value_s:${Array.isArray(slug) ? slug[0] : slug} && product_ids:${product_id}`)
                console.log("data response2 ",response2)
                return response2;
              }else if (category){ // belum bisa menangani lebih dari 1 category
                const response = await fetchVariantSolr(`id:${item.product_id} && category_name :${category}`);
                const product = response.response.docs[0];
                const product_id = product.id
                console.log("data brand ",brand)
                console.log("data respon varian ",product)
                console.log("data ID respon varian ",product_id)
                const response2 = await  fetchPromoItemsSolr( `type_value_s:${Array.isArray(slug) ? slug[0] : slug} && product_ids:${product_id}`)
                return response2;
              }else{
                const response = await fetchPromoItemsSolr( `id:${item.id}`)
                console.log("data respon",response)
                return response;
              }
              // if(brand || category){
              //   let query = `id:${item.product_id}`;
              //   if (brand) query += ` OR manufacture_name_s:${brand}`;
              //   if (category) query += ` OR category_name:${category}`;
              //   const response = await fetchVariantSolr(query);
              //   const product = response.response.docs[0];
              //   const product_id = product.id
              //   const response2 = await  fetchPromoItemsSolr( `type_value_s:${Array.isArray(slug) ? slug[0] : slug} && product_ids:${product_id}`)
              //   return response2;

              // }else{
              //   const response = await fetchPromoItemsSolr( `id:${item.id}`)
              //   console.log("data respon",response)
              //   return response;
              // }

      
          } catch (fetchError) {
            // console.error("Error fetching promotion data:", fetchError)
            return [];
          }
        });

        const promoDataArray = await Promise.all(promoDataPromises);
        const mergedPromoData = promoDataArray.reduce((accumulator, currentValue) => accumulator.concat(currentValue), []);
        setPromoData(mergedPromoData);

        const dataBrandCategoryPromises = promoDataArray.map(async (promoData) => {
          if (promoData) {
            const dataBrandCategory = promoData.map(async (item) => {
              // const response = await fetch(`/solr/variants/select?${queryParams2.toString()}`);
              let response;
              if(category){
                // response = await fetchVariantSolr(`id:${item.products[0].product_id} && manufacture_name_s:${brand}`);
                response = await fetchVariantSolr(`id:${item.products[0].product_id} && category_name:${category}`);
              }else{
                response = await fetchVariantSolr(`id:${item.products[0].product_id}`)    
              }
              

              if (response.response?.docs?.length > 0) {
                const product = response.response.docs[0];
                const manufactureNameS = product.manufacture_name;
                if (Array.isArray(manufactureNameS)) {
                  for (let i = 0; i < manufactureNameS.length; i += 2) {
                    const brand = manufactureNameS[i];
                    const qty = 1;
                    const existingBrandIndex = brandsData.findIndex(b => b.brand === brand);
                    if (existingBrandIndex !== -1) {
                      brandsData[existingBrandIndex].qty += qty;
                    } else {
                      brandsData.push({ brand, qty });
                    }
                  }
                }

                const categoryNameS = product.category_name;
                if (Array.isArray(categoryNameS)) {
                  for (let i = 0; i < categoryNameS.length; i += 2) {
                    const name = categoryNameS[i];
                    const qty = 1;
                    const existingCategoryIndex = categoriesData.findIndex(c => c.name === name);
                    if (existingCategoryIndex !== -1) {
                      categoriesData[existingCategoryIndex].qty += qty;
                    } else {
                      categoriesData.push({ name, qty });
                    }
                  }
                }
              }
            });

            return Promise.all(dataBrandCategory);
          }
        });

        await Promise.all(dataBrandCategoryPromises);
        setBrands(brandsData);
        setCategories(categoriesData);
        setLoading(false);

      } catch (loadError) {
        console.error("Error loading promo items:", loadError)
        setLoading(false);
      }
    }

    if (slug) {
      loadPromo()
    }
  }, [slug])

  const map = async (promotions: any[]): Promise<IPromotion[]> => {
    const result: IPromotion[] = []

    for (const promotion of promotions) {
      const data: IPromotion = {
        id: promotion.id,
        program_id: promotion.program_id_i,
        name: promotion.name_s,
        type: {
          value: promotion.type_value_s,
          label: promotion.type_label_s,
        },
        limit: promotion.package_limit_i,
        limit_user: promotion.package_limit_user_i,
        limit_trx: promotion.package_limit_trx_i,
        price: promotion.price_f,
        total_qty: promotion.total_qty_i,
        products: JSON.parse(promotion.products_s),
        free_products: JSON.parse(promotion.free_products_s),
      }

      result.push(data)
    }

    return result
  }

  function capitalizeFirstLetter(string) {
    string = string.replace(/_/g, ' ');
    return string.replace(/(^\w|\s\w)/g, function(match) {
        return match.toUpperCase();
    });
  }

  const visiblePromotions = promoData?.slice(0, currentPage * 12)
  const isNotReadyStockPage = router.asPath !== '/shop/promo?orderBy=stock';
  return (
    <BasicLayout>
      <Seo
        title={`Promo ${Array.isArray(slug) ? slug[0] : slug} Terkini`} 
        description='B2B Marketplace MRO & Industri dengan Layanan Pembayaran Tempo, Faktur Pajak, Online Quotation, Garansi Resmi & Harga Kompetitif'
      />
      <Promocrumb brandName={capitalizeFirstLetter(Array.isArray(slug) ? slug[0] : slug)} /> 
      <ProductFilterDesktop
              brands={brands || []}
              categories={categories || []}  
              prefixUrl={'/shop/promo'}
              defaultBrand={null}
            />
      {loading ? (
        <div className='container flex justify-center my-4'>
          <LogoSpinner width={48} height={48} />
        </div>
      ) : promoData && promoItems.length >= 1 ? (
        <>
          <div className=''>
            {visiblePromotions?.map((promotion) => (
              <div key={promotion.id} className="min-w-[400px] max-w-[400px] mb-[20px] sm:w-full md:w-1/2 lg:w-1/3 xl:w-1/4">
                <ProductPromoCard promotion={promotion}/>
              </div>
            ))}
          </div>
        </>
      ) : (
        <div className="text-center my-8">
          <p>Belum ada promo pada kategori ini</p>
        </div>
      )}
    </BasicLayout>
  )
}
